<template>
	<div style="position: relative;">
		<div style="margin-bottom: 100px;">
			<h3>登录</h3>
		</div>
		<van-form style="margin: 50px 0px;">
			<van-field v-model="account" name="用户名" label="用户名" placeholder="用户名" clearable/>
			<van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码" clearable/>
		</van-form>
		<div style="padding: 10px;">
			<van-button color="#0d8ddd" size="large" round @click="loginSubmit()">登录</van-button>
		</div>
	</div>
</template>

<script>
	import {
		userLogin,
		userInfo
	} from '@/api/user.js'

	export default {
		name: 'login',
		data() {
			return {
				account: '14761940053',
				password: '123456'
			}
		},
		created() {
			this.checkLogin()
		},
		methods: {
			checkLogin() {
				if (window.localStorage.getItem('hasLogin') == true) {
					this.$router.push({
						path: '/home'
					})
				}
			},
			loginSubmit() {
				if (this.account.length === 0) {
					this.$toast.fail('请输入账号')
				} else if (this.password.length === 0) {
					this.$toast.fail('请输入密码')
				} else {
					userLogin({
						username: this.account,
						password: this.password
					}).then(res => {
						if (res.code === 200) {
							console.log(res.token)
							window.localStorage.setItem('token', res.token)
							this.getUserInfo()
						} else {
							this.$toast.fail(res.msg)
						}
					})
				}
			},
			getUserInfo() {
				userInfo().then(res => {
					if (res.code == 200) {
						window.localStorage.setItem('carInfo',JSON.stringify(res.cars[0]))
					}
					window.localStorage.setItem('hasLogin',true);
					window.localStorage.setItem('userInfo',JSON.stringify(res.user))
					this.$router.push('/home')
				})
			}
		}
	}
</script>

<style>
</style>
